package com.liz.restfulApi.nettyDubbo.factory;

import com.liz.restfulApi.nettyDubbo.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lizhou on 2019/7/8.
 */
public class UserThreadLocalFactory {
    private final static Logger logger = LoggerFactory.getLogger(UserThreadLocalFactory.class);

    private static final ThreadLocal<User> userThreadLocal = new ThreadLocal<>();

    public UserThreadLocalFactory() {
    }

    /**
     * 使用双重检查锁来获得单例
     * Spring的IOC容器保证单例Bean并发访问时的安全性，基本上逻辑就是这样。
     * @return
     */
    public static  User getUser() {
        User user = userThreadLocal.get();
        if (null != user) {
            logger.info("直接获取到单例：user=" + user);
            return user;
        }
        synchronized (UserThreadLocalFactory.class){
            if(null != user){
                logger.info("同步锁里面获取到单例：user=" + user);
                return user;
            }
            user = new User();
            logger.info("new()了一个单例：user=" + user);
            userThreadLocal.set(user);
            return user;
        }
    }
}
